<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 左侧角色列表 -->
      <el-col :span="10">
        <el-collapse-transition>
          <el-card v-show="isFilterVisible" class="search-wrapper">
            <el-form :inline="true" :model="roleListParams">
              <el-form-item label="角色名称">
                <el-input
                  v-model="roleListParams.name"
                  clearable
                  placeholder="请输入角色名称"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-collapse-transition>
        <el-card class="box-card">
          <!-- 搜索区域 -->
          <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >{{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            />
          </el-button>
          <el-table
            :data="roleList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="角色名称" />
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleSetPermission(scope.row)"
                >去设置</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              background
              :current-page="roleListParams.page"
              :page-sizes="[10, 20, 30, 40, 50]"
              :page-size="roleListParams.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧权限设置 -->
      <el-col :span="14">
        <el-card class="box-card">
          <div slot="header">
            <span>{{ currentRole.name || "请选择角色" }}</span>
          </div>

          <el-table ref="menuTable" :data="menuList" style="width: 100%">
            <el-table-column label="菜单名称" min-width="180">
              <template slot-scope="scope">
                <div
                  class="menu-name-cell"
                  @click="handleExpand(scope.row, scope.$index)"
                >
                  <i
                    v-if="scope.row.list && scope.row.list.length"
                    :class="[
                      'el-icon-arrow-right',
                      { 'is-expand': scope.row.isExpand },
                    ]"
                  />
                  <span>{{ scope.row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="权限" width="100" align="center">
              <!-- <template slot-scope="scope">
                <el-checkbox
                  v-if="!scope.row.list || scope.row.list.length === 0"
                  v-model="scope.row.status"
                  :true-label="1"
                  :false-label="0"
                  @change="handleCheckboxChange(scope.row)"
                  >显示</el-checkbox
                >
              </template> -->
            </el-table-column>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div
                  v-if="scope.row.list && scope.row.list.length"
                  class="sub-menu-list"
                >
                  <div
                    v-for="item in scope.row.list"
                    :key="item.id"
                    class="sub-menu-item"
                  >
                    <span class="sub-menu-name">{{ item.name }}</span>
                    <el-checkbox
                      v-model="item.status"
                      :true-label="1"
                      :false-label="0"
                      @change="handleCheckboxChange(item)"
                    >显示</el-checkbox>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  selRoleListApi,
  selRoleMenuListByRoleIdApi,
  addRoleMenuApi,
  delRoleMenuByIdApi
} from '@/api/system'

export default {
  name: 'RolePermission',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      },
      // 角色列表
      roleList: [],
      // 总条数
      total: 0,
      // 当前选中的角色
      currentRole: {},
      // 权限树数据
      permissionList: [
        {
          id: '1',
          label: '首页-1',
          show: true
        },
        {
          id: '100',
          label: '系统管理-100',
          children: [
            {
              id: '100-1',
              label: '用户管理-100',
              show: false,
              add: true,
              edit: true,
              delete: true,
              save: true,
              search: true,
              export: true
            },
            {
              id: '110',
              label: '角色管理-110',
              show: false,
              add: true,
              edit: true,
              delete: true,
              save: true,
              search: true,
              export: true
            }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      isFilterVisible: false,
      // 角色列表参数
      roleListParams: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      menuList: [] // 菜单列表
    }
  },
  created() {
    this.selRoleList()
  },
  methods: {
    // 获取角色列表
    async selRoleList() {
      const res = await selRoleListApi(this.roleListParams)
      this.roleList = res.records
      this.total = res.total
    },
    // 查询
    handleQuery() {
      this.roleListParams.page = 1
      this.selRoleList()
    },
    // 重置
    resetQuery() {
      this.roleListParams = {
        page: 1,
        pageSize: 10,
        name: ''
      }
      this.selRoleList()
    },

    // 选择角色
    handleSelectionChange(selection) {
      this.currentRole = selection[0] || {}
    },
    // 设置权限
    async handleSetPermission(row) {
      this.currentRole = row
      const res = await selRoleMenuListByRoleIdApi(row.id)
      if (res.code === 1) {
        // 为每个菜单添加展开状态控制
        this.menuList = res.data.map((item) => ({
          ...item,
          isExpand: false
        }))
      }
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.roleListParams.pageSize = val
      this.selRoleList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.roleListParams.page = val
      this.selRoleList()
    },
    // checkbox变化
    async handleCheckboxChange(row) {
      console.log(row)
      try {
        if (row.status === 1) {
          const res = await addRoleMenuApi({
            roleId: this.currentRole.id,
            menuId: row.id
          })
          console.log(res)
          if (res.code === 1) {
            this.$message.success('设置成功')
          } else {
            this.$message.error(res.msg)
          }
        } else {
          const res1 = await delRoleMenuByIdApi({
            roleId: this.currentRole.id,
            menuId: row.id
          })
          if (res1.code === 1) {
            this.$message.success('设置成功')
          } else {
            this.$message.error(res1.msg)
          }
        }
      } catch (error) {
        this.$message.error('设置失败')
      }
    },
    // 处理展开/收起
    handleExpand(row, index) {
      if (row.list && row.list.length) {
        row.isExpand = !row.isExpand
        // 手动触发表格的展开/收起
        this.$refs.menuTable.toggleRowExpansion(row, row.isExpand)
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* .demo-form-inline {
  display: flex;
  justify-content: space-between;
} */

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.permission-options {
  display: flex;
  gap: 15px;
}

.permission-options .el-checkbox {
  margin-right: 0;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 120px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 33.33%;
}

.menu-permissions {
  padding: 20px;
}

.menu-title {
  font-weight: bold;
  margin-bottom: 15px;
}

.permission-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.permission-item {
  display: flex;
  align-items: center;
  width: calc(33.33% - 14px);
  min-width: 200px;
}

.permission-name {
  margin-right: 10px;
  color: #606266;
}

.permission-checkbox {
  margin-left: auto;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 60px;
  border-bottom: 1px solid #ebeef5;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-name {
  color: #606266;
}

.sub-menu-list {
  padding: 10px 20px;
}

.sub-menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.sub-menu-item:last-child {
  border-bottom: none;
}

.sub-menu-name {
  color: #606266;
}

.el-icon-arrow-right {
  margin-right: 8px;
  transition: transform 0.3s;
}

.el-icon-arrow-right.is-expand {
  transform: rotate(90deg);
}

/* 调整展开图标的位置 */
.el-table__expand-icon {
  display: none;
}

.menu-name-cell {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.menu-name-cell .el-icon-arrow-right {
  margin-right: 8px;
  transition: transform 0.3s;
}

.menu-name-cell .el-icon-arrow-right.is-expand {
  transform: rotate(90deg);
}

/* 隐藏表格默认的展开图标列 */
.el-table__expand-column {
  display: none;
}

/* 移除展开行的默认内边距 */
.el-table__expanded-cell {
  padding: 0 !important;
}
</style>
